package com.wenhai.leetcode.linkedList;

/**
 *https://leetcode-cn.com/problems/add-two-numbers/
 *
 * @author wenhai
 * @date   2021/4/2
 */
public class _2两数相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode dummyHead = new ListNode();
        ListNode lastNode = dummyHead;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int v1 = 0;
            int v2 = 0;
            if (l1 != null) {
                v1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                v2 = l2.val;
                l2 = l2.next;
            }
            lastNode.next = new ListNode((v1 + v2 + carry) % 10);
            lastNode = lastNode.next;
            carry = (v1 + v2 + carry) / 10;
        }
        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
